import RefreshIcon from '@mui/icons-material/Refresh'
import { IconButton, Tooltip } from '@mui/material'
import Box from '@mui/material/Box'
import { Eye, PlusIcon } from 'lucide-react'
import {
	type MRT_ColumnFiltersState,
	type MRT_PaginationState,
	type MRT_SortingState,
	type MRT_TableOptions,
	MaterialReactTable,
	useMaterialReactTable
} from 'material-react-table'
import { MRT_Localization_RU } from 'material-react-table/locales/ru'
import { useState } from 'react'

export function Table({
	columns,
	data,
	count,
	initSorting,
	isError,
	isRefetching,
	isLoading,
	refetch,
	defaultPinnedColumns,
	handleView,
	createBtn,
	...tableOptions
}: MRT_TableOptions<any> & {
	columns: any[]
	data: any[]
	count: number
	initSorting?: MRT_SortingState
	isError: boolean
	isRefetching: boolean
	isLoading: boolean
	refetch: () => void
	defaultPinnedColumns: string[]
	handleView: (id: number) => void
	createBtn?: { label: string; action: () => void }
}) {
	const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>([])
	const [globalFilter, setGlobalFilter] = useState('')
	const [sorting, setSorting] = useState<MRT_SortingState>(initSorting ?? [])
	const [pagination, setPagination] = useState<MRT_PaginationState>({
		pageIndex: 0,
		pageSize: 25
	})

	const table = useMaterialReactTable({
		...tableOptions,
		columns,
		data: data,
		initialState: {
			showColumnFilters: true,
			columnPinning: { left: defaultPinnedColumns ?? [] }
		},
		enableStickyHeader: true,
		enableColumnResizing: true,
		enableColumnPinning: true,
		muiTablePaperProps: ({ table }) => ({
			style: {
				zIndex: table.getState().isFullScreen ? 1201 : undefined
			}
		}),
		columnResizeMode: 'onEnd',
		// manualFiltering: true, // turn off built-in client-side filtering
		// manualPagination: true, // turn off built-in client-side pagination
		// manualSorting: true, // turn off built-in client-side sorting
		muiToolbarAlertBannerProps: isError
			? {
					color: 'error',
					children: 'Произошла ошибка при загрузке данных :('
				}
			: undefined,
		onColumnFiltersChange: setColumnFilters,
		onGlobalFilterChange: setGlobalFilter,
		onPaginationChange: setPagination,
		onSortingChange: setSorting,
		enableRowActions: true,
		renderRowActions: ({ row }) => (
			<Box>
				<Tooltip title='Подробнее'>
					<IconButton
						color={'primary'}
						onClick={() => handleView(row.original.id)}
					>
						<Eye />
					</IconButton>
				</Tooltip>
			</Box>
		),
		renderTopToolbarCustomActions: () => (
			<Box>
				{createBtn && (
					<Tooltip
						arrow
						title={createBtn.label}
					>
						<IconButton
							onClick={createBtn.action}
							color='success'
						>
							<PlusIcon />
						</IconButton>
					</Tooltip>
				)}
				<Tooltip
					arrow
					title='Обновить данные'
				>
					<IconButton onClick={() => refetch()}>
						<RefreshIcon />
					</IconButton>
				</Tooltip>
			</Box>
		),
		rowCount: count,
		state: {
			columnFilters,
			globalFilter,
			isLoading,
			pagination,
			showAlertBanner: isError,
			showProgressBars: isRefetching,
			sorting
		},
		localization: MRT_Localization_RU
	})

	return <MaterialReactTable table={table} />
}
